package com.xbjtech.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.User;
import com.xbjtech.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;
	
	/**
	 * 授权
	 */
	@SuppressWarnings("unused")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 登陆的校验过程
		log.info("token:{}", token.hashCode());
		UsernamePasswordToken loginUser = null;
		if (!(token instanceof UsernamePasswordToken)) {
			throw new AuthenticationException("登录信息有误");
		}
		loginUser = (UsernamePasswordToken) token;
		String username = loginUser.getUsername();
		User principal = userService.selectUserByUsername(username);
		if (principal == null) {
			// 用户名不存在
			throw new UnknownAccountException("用户名不存在");
		}
		ByteSource salt = ByteSource.Util.bytes(principal.getId() + "");
		return new SimpleAuthenticationInfo(principal, principal.getPassword(), salt, getName());
	}
	
	public static void main(String[] args) {
		// 计算密文
		SimpleHash simpleHash = new SimpleHash("SHA-256", "123456", ByteSource.Util.bytes(1L + ""), 1);
		System.out.println(simpleHash.toString());
	}
	
}
